package irc.controller;

import javax.swing.JInternalFrame;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import irc.view.TreeView;


/**
 * This class contains the actionListeners for the tree in the main frame. 
 * @author Jo
 * @since 1.8
 * @version 3.2
 */
public class TreeController {
	private TreeView tree;
	public BaseController CC;
	
	
	/**
	 * Constructor. Initializes its View, and gives itself to BaseController.
	 * @author Dybdal
	 * @since 1.8
	 * @version 2.8
	 */
	public TreeController(BaseController CC)	{
		tree = new TreeView(this);
		this.CC = CC;
		giveTreeToCC();	
	}
	
	
	/**
	 * ActionListener for the tree, as a single-selection listener. 
	 * @author Dybdal
	 * @since 1.1
	 */
	public void treeSelectionListener(final JTree tree){
		tree.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent e) { //gets the selected node
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
				if (node != null) { // if its not null
					String frameName = node.toString(); // gets the name
					JInternalFrame iframe = findFrame(frameName); // find the frame for the node
					if (iframe != null) {			// if frame is not null
						try {
							if(iframe.hasFocus()){ // if it have focus, minimize!
								iframe.setIcon(true);
							}
							else	{
							iframe.setIcon(false); // if it dont have focus maximize and puts it to the front
					        iframe.setSelected(true);
							}
						} catch (java.beans.PropertyVetoException pve) { }
					}
				}
			}
		});
		
	}
	
	
	/**
	 * Gives this class to BaseController
	 * @author Solveig
	 * @since 1.1
	 */
	public void giveTreeToCC(){
		CC.getTree(tree);
	}
	
	
	/** Finds the frame with the name in param
	 * @author Dybdal
	 * @since 1.1
	 * @return JInternalFrame
	 */
	public JInternalFrame findFrame(String name){
		for(int i = 0; i < CC.chanlist.size(); i++){ // loops trough the channellist
			if(name.equals(CC.chanlist.get(i).getName())){ // finds the right channel
				return CC.chanlist.get(i).getThis(); // returns the frame
			}
		}
		for(int i = 0; i < CC.chatlist.size(); i++){ // loops trough chatlist
			if(name.equals(CC.chatlist.get(i).getName())){ // finds the right priv frame
				return CC.chatlist.get(i).getThis();	// returns this
			}
		}
		return null; // returns null
	}
}
